import { useState, useEffect } from "react";
import Taro, { useReachBottom } from "@tarojs/taro";
import { View } from "@tarojs/components";
import { AtTabBar } from "taro-ui";
import "taro-ui/dist/style/components/button.scss"; // 按需引入
import "taro-ui/dist/style/components/tabs.scss";
import "taro-ui/dist/style/components/tab-bar.scss";
import "taro-ui/dist/style/components/badge.scss";
import Header from "@/components/header";
import MessageList from "@/components/MessageList";
import { getAnnouncementLists, getMessageLists } from "@/api/message";
import css from "./index.module.less";
import "./index.less";

export default function Message() {
  //是否有新消息
  const [annFlag, setAnnFlag] = useState(false);
  const [mesFlag, setMesFlag] = useState(false);
  const tabList = [
    { title: "系统公告", dot: annFlag },
    { title: "消息提醒", dot: mesFlag }
  ];
  const [current, setCurrent] = useState(0);
  const changeCurrent = value => {
    setCurrent(value);
  };
  const [messageData, setMessageData] = useState([]);
  const [announcementData, setAnnouncementData] = useState([]);

  // 跳转系统通知详情界面
  const toAnnouncementDetails = id => {
    Taro.navigateTo({ url: `announcement_details/index?id=${id}` });
  };
  // 跳转消息提醒详情界面
  const toRemindMessageDetails = id => {
    Taro.navigateTo({ url: `remid_message_details/index?id=${id}` });
    const currentMessage = messageData.filter((r) => r.id === id);
    const changeCurrentMessage = {
      "id": currentMessage[0].id,
      "state": 1,
      "content": currentMessage[0].content,
      "publishTime": currentMessage[0].publishTime
    };
    const newCurrentMessage = [];
    messageData.map((message) => {
      if (message.id === id) {
        newCurrentMessage.push(changeCurrentMessage);
      } else {
        newCurrentMessage.push(message);
      }
    });
    setMessageData(newCurrentMessage);
  };
  const [userInfo, setUserInfo] = useState({});

  //是否有新消息
  const isNew = (list) => {
    list.forEach(item => {
      if (item.state === 0) return true;
    });
    return false;
  };

  //轮询获取消息列表
  const [announcementPageData, setAnnouncementPageData] = useState({ page: 1, pageSize: 10 });
  const [messagePageData, setMessagePageData] = useState({ page: 1, pageSize: 10 });
  const intervalTime = 1000 * 60 * 3;

  async function getMessage(partyId) {
    let annRes = await getAnnouncementLists({ page: 1, pageSize: 10, partyId });
    let mesRes = await getMessageLists({ page: 1, pageSize: 10, partyId });
    if (mesRes.code === 502 || annRes.code === 502) {
      //超时
    }
    else if (mesRes.code !== 200 || annRes.code !== 200) {
      //错误
    }
    else {
      if (annRes.data.length !== 0) {
        setAnnFlag(isNew(annRes.data));
      }
      if (mesRes.data.length !== 0) {
        setMesFlag(isNew(annRes.data));
      }
      setAnnouncementPageData({ page: 1, pageSize: 10 });
      setMessagePageData({ page: 1, pageSize: 10 });
      setAnnouncementData(annRes.data);
      setMessageData(mesRes.data);
    }
  }

  // 获取消息列表
  useEffect(() => {
    Taro.getStorage({
      key: 'userInfo',
      success: function (a) {
        setUserInfo(a.data);
        getMessage(a.data.partyId);
        const timer = setInterval( getMessage, intervalTime, a.data.partyId );
        return () => { clearInterval(timer); };
      }
    });
  }, []);

  useReachBottom(() => {
    const partyId = userInfo.partyId;
    if (current === 0) {
      setAnnouncementPageData({ page: announcementPageData.page + 1, pageSize: 5 });
      getAnnouncementLists({ ...announcementPageData, partyId: partyId }).then((res) => {
        if (res.code === 200) {
          const newData = announcementData.concat(res.data);
          setAnnouncementData(newData);
        }
      });
    }
    if (current === 1) {
      setMessagePageData({ page: messagePageData.page + 1, pageSize: 5 });
      getMessageLists({ ...messagePageData, partyId: partyId }).then((res) => {
        if (res.code === 200) {
          const newData = messageData.concat(res.data);
          setMessageData(newData);
        }
      });
    }
  });
  return (
    <View className={css.app}>
      <Header message='消息' left='162px' />
      <View className={css.content}>
        <AtTabBar tabList={tabList} current={current} onClick={changeCurrent} className={css.bar} />
        {current === 0 ? (
          <View>
            {announcementData.map(item => {
              return (
                <View key={item.id} onClick={() => toAnnouncementDetails(item.id)}>
                  <MessageList value={{ title: item.content, date: item.publishedTime, isRead: item.state === 1 ? true : false }} />
                </View>
              );
            })}
          </View>
        ) : (
          <View>
            {messageData.map(item => {
              return (
                <View key={item.id} onClick={() => toRemindMessageDetails(item.id)}>
                  <MessageList value={{ title: item.content, date: item.publishTime, isRead: item.state === 1 ? true : false }} />
                </View>
              );
            })}
          </View>
        )}
      </View>
    </View>
  );
}
